package leetcode;

import lombok.Data;

/**
 * @Author: wqf
 * @Date: 2023/11/21
 * @Description:
 */
public class _0019_删除链表的倒数第N个节点 {

    public static void main(String[] args) {
        ListNode head = new ListNode(1,new ListNode(2,new ListNode(3, new ListNode(4,new ListNode(5,new ListNode(6))))));
        System.out.println(removeNthFromEnd(head, 2));;
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummyNode = new ListNode(0);
        dummyNode.next = head;

        ListNode fastIndex = dummyNode;
        ListNode slowIndex = dummyNode;

        // 只要快慢指针相差 n 个结点即可 ，该节点后的节点对象
        for (int i = 0; i <= n; i++) {
            fastIndex = fastIndex.next;
        }

        while (fastIndex != null) {
            fastIndex = fastIndex.next;
            slowIndex = slowIndex.next;
        }

        //此时 slowIndex 的位置就是待删除元素的前一个位置。
        //具体情况可自己画一个链表长度为 3 的图来模拟代码来理解
        slowIndex.next = slowIndex.next.next;
        return dummyNode.next;
    }
}

@Data
class ListNode {
    /**
     * 当前节点值
     */
    protected Integer node;
    /**
     * 下一个节点对象
     */
    protected ListNode next;

    public ListNode(Integer node) {
        this.node = node;
    }

    public ListNode(Integer node, ListNode next) {
        this.node = node;
        this.next = next;
    }
}
